package com.us.usws.batch;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.us.usws.batch.resimp.result.FailureCellResult;
import com.us.usws.batch.resimp.result.ResImpResult;

public class BatchUtils {

	public static final String ADMIN_UID = "36da97e83fe15205c17e077b";

	public static String getImpOutput(ResImpResult result) {
		if (result == null) {
			return "";
		}

		StringBuilder sb = new StringBuilder();
		sb.append("操作名称：").append(result.getTitle()).append("<br>");
		sb.append("文件路径：").append(result.getFilePath()).append("<br>");
		sb.append("结果描述：").append(result.getSummaryMsg()).append("<br>");
		sb.append("成功条数：").append(result.getSuccessCnt()).append("，失败条数：").append(result.getFailureCnt()).append("<br>");
		sb.append(getFailure(result.getFailures()));
		sb.append(getThrowable(result.getEx()));
		return sb.toString();
	}

	private static String getThrowable(Throwable t) {
		if (t == null) {
			return "";
		}

		StringBuilder sb = new StringBuilder();

		StackTraceElement[] trace = t.getStackTrace();
		for (StackTraceElement te : trace) {
			sb.append(te);
		}

		//suppressed
		for (Throwable se : t.getSuppressed()) {
			sb.append(getThrowable(se));
		}

		//cause
		Throwable c = t.getCause();
		if (c != null) {
			sb.append(getThrowable(c));
		}

		return sb.toString();
	}

	private static String getFailure(List<FailureCellResult> failures) {
		StringBuilder sb = new StringBuilder();
		if (failures != null && !failures.isEmpty()) {
			sb.append("以下为失败明细：<br>");
			Map<String, List<FailureCellResult>> m = new HashMap<>();
			for (FailureCellResult each : failures) {
				if (m.containsKey(each.getFilePath())) {
					m.get(each.getFilePath()).add(each);
				} else {
					List<FailureCellResult> one = new ArrayList<>();
					one.add(each);
					m.put(each.getFilePath(), one);
				}
			}
			//for map
			for (String key : m.keySet()) {
				if (StringUtils.isNotBlank(key)) {
					sb.append("文件：").append(key).append("<br>");
				}
				sb.append("{<br>");
				for (FailureCellResult fs : m.get(key)) {
					sb.append("&nbsp;&nbsp;&nbsp;&nbsp;行：").append(fs.getRow() == 0 ? "多处" : fs.getRow());
					if (fs.getCol() > 0) {
						sb.append("，列：").append(fs.getCol());
					}
					sb.append("，错误：").append(fs.getFailMsg()).append("<br>");
				}
				sb.append("}<br>");
			}
		}
		return sb.toString();
	}
}
